(function (window, $, undefined) {
  'use strict';

  // 备选城市列表
  var cityLists = [];
  // 已添加城市列表数据
  var cityData = {};

  // 当前处理中的城市编号
  var curCityId = '';
  // 当前处理中的机场编号
  var curAirportId = '';

  // 机场数据
  var airportData = {};
  // 航站楼数据
  var terminalData = {};
  // 航站楼泊车位数据
  var parkingDataA = {};

  // 站点数据
  var stationData = {};
  // 出站口数据
  var stationExitData = {};
  // 出站口泊车位数据
  var stationParkingData = {};

  main(function () {

    // 备选城市列表的获取
    $.each(PC_CODE.sort(function (a, b) {
      return +a.adcode > +b.adcode ? 1 : -1
    }), function (_, item) {
      if (item.code !== '000') {
        cityLists.push({
          id: item.adcode.substr(0, 4),
          name: item.city
        });
      }
    });

    var $cityList = $('.citylist>.row');

    $cityList.on('click', '.city-op>span', function () {
      var $this = $(this);
      var index = $this.index();
      var id = $this.parents('.city-item').data('cid');
      var name = $this.parent().siblings('.city-name').text();
      if (index === 0) {
        openAirport(id, name);
      } else if (index === 1) {
        openStation(id, name);
      } else {
        openBusiness(id, name);
      }
      curCityId = id;
    });

    // 获取城市列表
    getCityList();
    function getCityList(callback) {

      util.ajax(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', '', 'GET', util.resCallback(function (res) {
        var ret = '';
        cityData = {};
        $.each(res.data, function (_, item) {
          cityData[item.cityId] = item;
          ret += '<div class="col-xs-3"><div class="city-item" data-cid="' + item.cityId + '" data-kid="' + item.kid + '"><div class="city-name">' + item.name + '</div><div class="city-detail" title="查看/编辑"><i class="fa fa-edit fa-2x"></i></div><div class="city-del" title="删除"><i class="fa fa-close fa-3x"></i></div><div class="city-op"><span>机场设置</span><span>站务设置</span><span>商圈设置</span></div></div></div>';
        });
        $cityList.find('.col-xs-3').not('.first').remove();
        $cityList.prepend(ret);

        if ($.isFunction(callback)) {
          callback();
        }
      }));
    }

    var $layerAirport = $('#layer-airport');
    var $layerStation = $('#layer-station');

    // 机场设置
    function openAirport(id, name) {
      // 根据 id 获取相关信息
      // 查询城市对应的机场
      getAirportList(id, function () {
        util.layerOpen({
          title: '机场设置&emsp;城市：' + name,
          content: $layerAirport,
          area: ['800px', '']
        });
      });

    }

    // 渲染机场列表
    var $airportList = $('#airport-list');
    function getAirportList(id, callback) {
      $airportList.empty();
      util.ajax(ajaxURL.ORGANIZATION + '/airport/getAirportList', {
        cityId: id
      }, 'GET', util.resCallback(function (res) {
        var ret = '';
        $.each(res.data, function (_, item) {
          airportData[item.kid] = item;

          ret += '<li data-kid="' + item.kid + '">';
          ret += '<span class="marginR10">' + item.name + '</span>';
          ret += '<button class="btn btn-default marginR10 airport-view" type="button"><span>查看/修改</span></button>';
          ret += '<button class="btn btn-default marginR10 airport-terminal" type="button"><span>航站楼管理</span></button>';
          ret += '<button class="btn btn-default marginR10 airport-parking" type="button"><span>泊车位管理</span></button>';

          if (res.data.length > 1) {
            ret += '<button class="btn btn-default marginR10 airport-del" type="button"><span>删除</span></button>';
          }
          ret += '</li>';
        });

        $airportList.html(ret);

        if ($.isFunction(callback)) {
          callback();
        }

      }));
    }

    var $layerAirportDetail = $('#layer-airport-detail');
    var $formAirport = $('#form-airport');

    var $valiateAirport = $formAirport.validate({
      rules: {
        name: { required: true },
        tel: { required: true },
        address: { required: true },
        manager: { required: true },
        managerPhone: { required: true },
        lat: { required: true },
        lng: { required: true },
        range: { required: true },
        pickupGuide: { required: true },
        sendGuide: { required: true }
      },
      messages: {
        name: { required: '请输入机场名称' },
        tel: { required: '请输入机场电话' },
        address: { required: '请输入机场地址' },
        manager: { required: '请输入管理员姓名' },
        managerPhone: { required: '请输入管理员电话' },
        lat: { required: '请输入机场纬度' },
        lng: { required: '请输入机场经度' },
        range: { required: '请输入坐标范围' },
        pickupGuide: { required: '请输入接机引导' },
        sendGuide: { required: '请输入送机引导' }
      }
    });

    // 新增机场
    $('#airport-add').click(function () {
      util.resetForm($formAirport);

      $('#pick-aiport-address').data({lng: '', lat: ''});

      util.layerOpen2({
        title: '新增机场',
        content: $layerAirportDetail,
        area: ['800px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          // 保存操作
          var data = util.formData($formAirport);
          // 数据补充
          data.status = 101;
          data.cityId = curCityId;
          // 新增时不要 kid
          data.kid = '';

          if ($valiateAirport.form()) {
            layer.confirm('确定新增机场？', function () {
              util.ajax(ajaxURL.ORGANIZATION + '/airport/addAirport', JSON.stringify(data), 'POST', util.resCallback(function (res) {
                getAirportList(curCityId, function () {
                  layer.close(index);
                  util.tip.success('新增成功');
                });
              }));
            });
          }
        }
      });
    });

    // 机场的查看/修改操作
    $layerAirport.on('click', '.airport-view', function () {
      var id = $(this).parent().data('kid');
      util.resetForm($formAirport);

      var curAirportData = airportData[id];
      util.fillForm($formAirport, curAirportData);

      $('#pick-aiport-address').data({ lng: curAirportData.lng, lat: curAirportData.lat });

      util.layerOpen2({
        title: '查看/修改机场',
        content: $layerAirportDetail,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          // 保存操作
          var data = util.formData($formAirport);
          // 数据补充
          data.status = 101;
          data.cityId = curCityId;

          if ($valiateAirport.form()) {
            layer.confirm('确定修改机场信息？', function () {
              util.ajax(ajaxURL.ORGANIZATION + '/airport/updateAirport', JSON.stringify(data), 'POST', util.resCallback(function (res) {
                getAirportList(curCityId, function () {
                  layer.close(index);
                  util.tip.success('修改成功');
                });
              }));
            });
          }
        }
      });
    });

    // 删除机场操作
    $layerAirport.on('click', '.airport-del', function () {
      var id = $(this).parent().data('kid');
      layer.confirm('确定删除该机场？删除后相关的数据将全部失效，请谨慎操作', function () {
        util.ajax(ajaxURL.ORGANIZATION + '/airport/removeAirport?kid=' + id, '', 'POST', util.resCallback(function (res) {
          getAirportList(curCityId, function () {
            util.tip.success('删除成功');
          });
        }));
      });
    });

    // 航站楼管理
    var $layerTerminal = $('#layer-airport-terminal');
    $layerAirport.on('click', '.airport-terminal', function () {
      curAirportId = $(this).parent().data('kid');

      getTerminalList(curAirportId, function () {
        util.layerOpen({
          title: '航站楼管理',
          content: $layerTerminal,
          area: ['800px', '']
        });
      });

    });

    // 获取航站楼列表
    var $terminalList = $('#terminal-list');
    function getTerminalList(id, callback) {
      $terminalList.empty();
      util.get(ajaxURL.ORGANIZATION + '/airport/getAirportTerminalList', {
        cityId: curCityId
      }, function (res) {
        // 后台接口问题，无法过滤机场 id，这里强行过滤一下
        var data = res.data.filter(function (v) {
          return v && v.airportId === +id && v.status === 101;
        });

        var ret = '';
        terminalData = {};
        $.each(data, function (_, item) {
          terminalData[item.kid] = item;

          ret += '<li data-kid="' + item.kid + '">';
          ret += '<span class="marginR10">' + item.name + '</span>';
          ret += '<button class="btn btn-default marginR10 terminal-view" type="button"><span>修改</span></button>';

          if (data.length > 1) {
            ret += '<button class="btn btn-default marginR10 terminal-del" type="button"><span>删除</span></button>';
          }
          ret += '</li>';
        });

        $terminalList.html(ret);

        if ($.isFunction(callback)) {
          callback(res);
        }

      });
    }

    // 删除航站楼
    $layerTerminal.on('click', '.terminal-del', function () {
      var id = $(this).parent().data('kid');
      layer.confirm('确定删除该航站楼？', function () {
        util.post(ajaxURL.ORGANIZATION + '/airport/removeAirportTerminal?kid=' + id, function (res) {
          getTerminalList(curAirportId, function () { util.tip.success('删除成功'); });
        });
      });
    });

    var $layerTerminalDeail = $('#layer-terminal-detail');
    var $formTerminal = $('#form-terminal');

    var $valiateTerminal = $formTerminal.validate({
      rules: {
        name: { required: true },
        lat: { required: true },
        lng: { required: true },
      },
      messages: {
        name: { required: '请输入机场名称' },
        lat: { required: '请输入机场纬度' },
        lng: { required: '请输入机场经度' }
      }
    });

    // 新增航站楼
    $('#terminal-add').click(function () {
      util.resetForm($formTerminal);
      $('#pick-terminal-address').data({ lng: airportData[curAirportId].lng, lat: airportData[curAirportId].lat });
      util.layerOpen2({
        title: '新增航站楼',
        content: $layerTerminalDeail,
        area: ['800px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          var data = util.formData($formTerminal);
          data.kid = '';
          data.status = 101;
          data.airportId = curAirportId;
          data.cityId = curCityId;
          data.airportName = airportData[curAirportId].name;

          if ($valiateTerminal.form()) {
            layer.confirm('确定新增航站楼？', function () {
              util.post(ajaxURL.ORGANIZATION + '/airport/addAirportTerminal', data, function (res) {
                getTerminalList(curAirportId, function () {
                  layer.close(index);
                  util.tip.success('新增成功');
                });
              });
            });
          }
        }
      });
    });

    // 修改航站楼
    $layerTerminal.on('click', '.terminal-view', function () {
      util.resetForm($formTerminal);
      var id = $(this).parent().data('kid');
      util.fillForm($formTerminal, terminalData[id]);
      $('#pick-terminal-address').data({ lng: terminalData[id].lng, lat: terminalData[id].lat });
      util.layerOpen2({
        title: '查看/修改航站楼',
        content: $layerTerminalDeail,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          var data = util.formData($formTerminal);
          data.status = 101;
          data.airportId = curAirportId;
          data.cityId = curCityId;
          data.airportName = airportData[curAirportId].name;

          if ($valiateTerminal.form()) {
            layer.confirm('确定修改该航站楼？', function () {
              util.post(ajaxURL.ORGANIZATION + '/airport/updateAirportTerminal', data, function (res) {
                getTerminalList(curAirportId, function () {
                  layer.close(index);
                  util.tip.success('修改成功');
                });
              });
            });
          }
        }
      });
    });

    // 机场泊车位管理
    var $layerAirportParking = $('#layer-airport-parking');
    var $formAirportParking = $('#form-airport-parking');
    var $layerAirportParkingDetail = $('#layer-airport-parking-detail');
    var $valiateAirportParking = $formAirportParking.validate({
      rules: {
        name: { required: true },
        airportTerminalId: { required: true }
      },
      messages: {
        name: { required: '请输入泊车位名称' },
        airportTerminalId: { required: '请选择航站楼' }
      }
    });

    // 机场泊车位
    var $airportParkingList = $('#airport-parking-list');
    $layerAirport.on('click', '.airport-parking', function () {
      curAirportId = $(this).parent().data('kid');
      getTerminalList(curAirportId, function (curRes) {

        var data = curRes.data.filter(function (v) {
          return v && v.airportId === +curAirportId && v.status === 101;
        });

        util.selectHtml($layerAirportParkingDetail.find('[name="airportTerminalId"]'), data, 'kid', 'name', '请选择');

        if (data.length > 0) {

          getAirportParking(curAirportId, function () {
            util.layerOpen2({
              title: '泊车位管理',
              content: $layerAirportParking,
              area: ['800px', '']
            });
          });


        } else {
          util.tip.warn('暂无航站楼，请先添加航站楼');
        }
      });
    });

    function getAirportParking(id, callback) {
      $airportParkingList.empty();
      util.get(ajaxURL.ORGANIZATION + '/airport/getAirportParkingList', {
        airportId: id
      }, function (res) {
        var ret = '';

        // 后台未过滤状态，这里强行过滤一番
        var data = res.data.filter(function (v) {
          return v.status === 101;
        });

        $.each(data, function (_, item) {

          parkingDataA[item.kid] = item;

          ret += '<li data-name="' + item.name + '" data-tid="' + item.airportTerminalId + '" data-kid="' + item.kid + '">';
          ret += '<span class="marginR10">泊车位名称：' + item.name + '</span>';
          ret += '<span class="marginR10">航站楼名称：' + terminalData[item.airportTerminalId].name + '</span>';
          ret += '<button class="btn btn-default marginR10 airport-parking-view" type="button"><span>修改</span></button>';

          if (data.length > 1) {
            ret += '<button class="btn btn-default marginR10 airport-parking-del" type="button"><span>删除</span></button>';
          }
          ret += '</li>';
        });
        $airportParkingList.html(ret);

        if ($.isFunction(callback)) {
          callback(res);
        }

      });
    }

    // 新增机场泊车位
    $('#airport-parking-add').click(function () {
      util.resetForm($formAirportParking);
      util.layerOpen2({
        title: '新增泊车位',
        content: $layerAirportParkingDetail,
        area: ['800px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          var data = util.formData($formAirportParking);
          data.kid = '';
          data.cityId = curCityId;
          data.airportId = curAirportId;

          if ($valiateAirportParking.form()) {
            layer.confirm('确定新增泊车位？', function () {
              util.post(ajaxURL.ORGANIZATION + '/airport/addAirportParking', data, function (res) {
                getAirportParking(curAirportId, function () {
                  layer.close(index);
                  util.tip.success('新增成功');
                });
              });
            });
          }
        }
      });
    });

    // 修改机场泊车位
    $layerAirportParking.on('click', '.airport-parking-view', function () {
      util.resetForm($formAirportParking);
      var id = $(this).parent().data('kid');
      var curData = parkingDataA[id];

      util.fillForm($formAirportParking, curData);
      util.layerOpen2({
        title: '修改泊车位',
        content: $layerAirportParkingDetail,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          var data = util.formData($formAirportParking);
          data.kid = curData.kid;
          data.cityId = curCityId;
          data.airportId = curAirportId;

          if ($valiateAirportParking.form()) {
            layer.confirm('确定修改该泊车位？', function () {
              util.post(ajaxURL.ORGANIZATION + '/airport/updateAirportParking', data, function (res) {
                getAirportParking(curAirportId, function () {
                  layer.close(index);
                  util.tip.success('修改成功');
                });
              });
            });
          }
        }
      });
    });

    // 删除机场泊车位
    $layerAirportParking.on('click', '.airport-parking-del', function () {
      var id = $(this).parent().data('kid');
      layer.confirm('确定删除该机场泊车位？', function () {
        util.post(ajaxURL.ORGANIZATION + '/airport/removeAirportParking?kid=' + id, function (res) {
          getAirportParking(curAirportId, function () {
            util.tip.success('删除成功');
          });
        });
      });
    });

    // 站务设置
    function openStation(id, name) {
      getStationList(id, function () {
        util.layerOpen({
          title: '站务设置&emsp;城市：' + name,
          content: $layerStation,
          area: ['800px', '']
        });
      });
    }

    // 站点列表
    var $stationList = $('#station-list');
    function getStationList(id, callback) {
      $stationList.empty();
      util.ajax(ajaxURL.ORGANIZATION + '/station/getStationList', {
        cityId: id
      }, 'GET', util.resCallback(function (res) {
        var ret = '';
        $.each(res.data, function (_, item) {
          stationData[item.kid] = item;

          ret += '<li data-kid="' + item.kid + '">';
          ret += '<span class="marginR10">' + item.name + '</span>';
          ret += '<button class="btn btn-default marginR10 station-view" type="button"><span>查看/修改</span></button>';
          ret += '<button class="btn btn-default marginR10 station-exit" type="button"><span>出站口管理</span></button>';
          ret += '<button class="btn btn-default marginR10 station-parking" type="button"><span>泊车位管理</span></button>';

          if (res.data.length > 1) {
            ret += '<button class="btn btn-default marginR10 station-del" type="button"><span>删除</span></button>';
          }
          ret += '</li>';
        });

        $stationList.html(ret);

        if ($.isFunction(callback)) {
          callback(res);
        }
      }));
    }

    var $layerStationDetail = $('#layer-station-detail');
    var $formStation = $('#form-station');

    var $valiateStation = $formStation.validate({
      rules: {
        name: { required: true },
        tel: { required: true },
        address: { required: true },
        manager: { required: true },
        managerPhone: { required: true },
        lat: { required: true },
        lng: { required: true },
        range: { required: true },
        pickupGuide: { required: true },
        sendGuide: { required: true }
      },
      messages: {
        name: { required: '请输入站点名称' },
        tel: { required: '请输入站点电话' },
        address: { required: '请输入站点地址' },
        manager: { required: '请输入管理员姓名' },
        managerPhone: { required: '请输入管理员电话' },
        lat: { required: '请输入站点纬度' },
        lng: { required: '请输入站点经度' },
        range: { required: '请输入坐标范围' },
        pickupGuide: { required: '请输入接站引导' },
        sendGuide: { required: '请输入送站引导' }
      }
    });

    // 新增站点
    $('#station-add').click(function () {
      util.resetForm($formStation);

      $('#pick-station-address').data({ lng: '', lat: '' });

      util.layerOpen2({
        title: '新增站点',
        content: $layerStationDetail,
        area: ['800px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          // 保存操作
          var data = util.formData($formStation);
          // 数据补充
          data.status = 101;
          data.cityId = curCityId;
          // 新增时不要 kid
          data.kid = '';

          if ($valiateStation.form()) {
            layer.confirm('确定新增站点？', function () {
              util.ajax(ajaxURL.ORGANIZATION + '/station/addStation', JSON.stringify(data), 'POST', util.resCallback(function (res) {
                getStationList(curCityId, function () {
                  layer.close(index);
                  util.tip.success('新增成功');
                });
              }));
            });
          }
        }
      });
    });

    // 站点的查看/修改操作
    $layerStation.on('click', '.station-view', function () {
      var id = $(this).parent().data('kid');
      util.resetForm($formStation);
      util.fillForm($formStation, stationData[id]);

      $('#pick-station-address').data({ lng: stationData[id].lng, lat: stationData[id].lat });

      util.layerOpen2({
        title: '查看/修改站点',
        content: $layerStationDetail,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          // 保存操作
          var data = util.formData($formStation);
          // 数据补充
          data.status = 101;
          data.cityId = curCityId;

          if ($valiateStation.form()) {
            layer.confirm('确定修改站点信息？', function () {
              util.ajax(ajaxURL.ORGANIZATION + '/station/updateStation', JSON.stringify(data), 'POST', util.resCallback(function (res) {
                getStationList(curCityId, function () {
                  layer.close(index);
                  util.tip.success('修改成功');
                });
              }));
            });
          }
        }
      });
    });

    // 删除站点操作
    $layerStation.on('click', '.station-del', function () {
      var id = $(this).parent().data('kid');
      layer.confirm('确定删除该站点？删除后相关的数据将全部失效，请谨慎操作', function () {
        util.ajax(ajaxURL.ORGANIZATION + '/station/removeStation?kid=' + id, '', 'POST', util.resCallback(function (res) {
          getStationList(curCityId, function () {
            util.tip.success('删除成功');
          });
        }));
      });
    });

    // 出站口管理
    var $layerStationExit = $('#layer-station-exit');
    var curStationId = '';
    $layerStation.on('click', '.station-exit', function () {
      curStationId = $(this).parent().data('kid');

      getStationExitList(curStationId, function () {
        util.layerOpen({
          title: '出站口管理',
          content: $layerStationExit,
          area: ['800px', '']
        });
      });

    });

    // 获取出站口列表
    var $sationExitList = $('#station-exit-list');

    function getStationExitList(id, callback) {
      $sationExitList.empty();
      util.get(ajaxURL.ORGANIZATION + '/station/getStationExitList', {
        cityId: curCityId
      }, function (res) {
        // 后台接口问题，无法过滤站点 id，这里强行过滤一下
        var data = res.data.filter(function (v) {
          return v && v.stationId === +id && v.status === 101;
        });

        var ret = '';
        stationExitData = {};
        $.each(data, function (_, item) {
          stationExitData[item.kid] = item;

          ret += '<li data-kid="' + item.kid + '">';
          ret += '<span class="marginR10">' + item.name + '</span>';
          ret += '<button class="btn btn-default marginR10 station-exit-view" type="button"><span>修改</span></button>';

          if (data.length > 1) {
            ret += '<button class="btn btn-default marginR10 station-exit-del" type="button"><span>删除</span></button>';
          }
          ret += '</li>';
        });

        $sationExitList.html(ret);

        if ($.isFunction(callback)) {
          callback(res);
        }

      });
    }

    // 删除出站口
    $layerStationExit.on('click', '.station-exit-del', function () {
      var id = $(this).parent().data('kid');
      layer.confirm('确定删除该出站口？', function () {
        util.post(ajaxURL.ORGANIZATION + '/station/removeStationExit?kid=' + id, function (res) {
          getStationExitList(curStationId, function () {
            util.tip.success('删除成功');
          });
        });
      });
    });

    var $layerStationExitDetail = $('#layer-station-exit-detail');
    var $formStationExit = $('#form-station-exit');

    var $valiateStationExit = $formStationExit.validate({
      rules: {
        name: { required: true },
        lat: { required: true },
        lng: { required: true },
      },
      messages: {
        name: { required: '请输入站点名称' },
        lat: { required: '请输入站点纬度' },
        lng: { required: '请输入站点经度' }
      }
    });

    // 新增出站口
    $('#station-exit-add').click(function () {
      util.resetForm($formStationExit);
      $('#pick-station-exit-address').data({ lng: stationData[curStationId].lng, lat: stationData[curStationId].lat });
      util.layerOpen2({
        title: '新增出站口',
        content: $layerStationExitDetail,
        area: ['800px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          var data = util.formData($formStationExit);
          data.kid = '';
          data.status = 101;
          data.stationId = curStationId;
          data.cityId = curCityId;
          data.stationName = stationData[curStationId].name;

          if ($valiateStationExit.form()) {
            layer.confirm('确定新增出站口？', function () {
              util.post(ajaxURL.ORGANIZATION + '/station/addStationExit', data, function (res) {
                getStationExitList(curStationId, function () {
                  layer.close(index);
                  util.tip.success('新增成功');
                });
              });
            });
          }
        }
      });
    });

    // 修改出站口
    $layerStationExit.on('click', '.station-exit-view', function () {
      util.resetForm($formStationExit);
      var id = $(this).parent().data('kid');
      util.fillForm($formStationExit, stationExitData[id]);

      $('#pick-station-exit-address').data({ lng: stationExitData[id].lng, lat: stationExitData[id].lat });

      util.layerOpen2({
        title: '查看/修改出站口',
        content: $layerStationExitDetail,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          var data = util.formData($formStationExit);
          data.status = 101;
          data.stationId = curStationId;
          data.cityId = curCityId;
          data.stationName = stationData[curStationId].name;

          if ($valiateStationExit.form()) {
            layer.confirm('确定修改该出站口？', function () {
              util.post(ajaxURL.ORGANIZATION + '/station/updateStationExit', data, function (res) {
                getStationExitList(curStationId, function () {
                  layer.close(index);
                  util.tip.success('修改成功');
                });
              });
            });
          }
        }
      });
    });

    // 站点泊车位管理
    var $layerStationParking = $('#layer-station-parking');
    var $formStationParking = $('#form-station-parking');
    var $layerStationParkingDetail = $('#layer-station-parking-detail');
    var $valiateStationParking = $formStationParking.validate({
      rules: {
        name: { required: true },
        stationTerminalId: { required: true }
      },
      messages: {
        name: { required: '请输入泊车位名称' },
        stationTerminalId: { required: '请选择航站楼' }
      }
    });

    // 站点泊车位
    var $stationParkingList = $('#station-parking-list');
    $layerStation.on('click', '.station-parking', function () {
      curStationId = $(this).parent().data('kid');
      getStationExitList(curStationId, function (curRes) {

        var data = curRes.data.filter(function (v) {
          return v && v.stationId === +curStationId && v.status === 101;
        });

        util.selectHtml($layerStationParkingDetail.find('[name="stationExitId"]'), data, 'kid', 'name', '请选择');

        if (data.length > 0) {

          getStationParking(curStationId, function () {
            util.layerOpen2({
              title: '泊车位管理',
              content: $layerStationParking,
              area: ['800px', '']
            });
          });

        } else {
          util.tip.warn('暂无出站口，请先添加出站口');
        }
      });
    });

    function getStationParking(id, callback) {
      $stationParkingList.empty();
      util.get(ajaxURL.ORGANIZATION + '/station/getStationParkingList', {
        stationId: id
      }, function (res) {
        var ret = '';

        // 后台未过滤状态，这里强行过滤一番
        var data = res.data.filter(function (v) {
          return v.status === 101;
        });

        $.each(data, function (_, item) {

          stationParkingData[item.kid] = item;

          ret += '<li data-name="' + item.name + '" data-tid="' + item.stationExitId + '" data-kid="' + item.kid + '">';
          ret += '<span class="marginR10">泊车位名称：' + item.name + '</span>';
          ret += '<span class="marginR10">出站口名称：' + stationExitData[item.stationExitId].name + '</span>';
          ret += '<button class="btn btn-default marginR10 station-parking-view" type="button"><span>修改</span></button>';

          if (data.length > 1) {
            ret += '<button class="btn btn-default marginR10 station-parking-del" type="button"><span>删除</span></button>';
          }
          ret += '</li>';
        });
        $stationParkingList.html(ret);

        if ($.isFunction(callback)) {
          callback(res);
        }
      });
    }

    // 新增站点泊车位
    $('#station-parking-add').click(function () {
      util.resetForm($formStationParking);
      util.layerOpen2({
        title: '新增泊车位',
        content: $layerStationParkingDetail,
        area: ['800px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          var data = util.formData($formStationParking);
          data.kid = '';
          data.cityId = curCityId;
          data.stationId = curStationId;

          if ($valiateStationParking.form()) {
            layer.confirm('确定新增泊车位？', function () {
              util.post(ajaxURL.ORGANIZATION + '/station/addStationParking', data, function (res) {

                getStationParking(curStationId, function () {
                  layer.close(index);
                  util.tip.success('新增成功');
                });
              });
            });
          }
        }
      });
    });

    // 修改站点泊车位
    $layerStationParking.on('click', '.station-parking-view', function () {
      util.resetForm($formStationParking);
      var id = $(this).parent().data('kid');
      var curData = stationParkingData[id];

      util.fillForm($formStationParking, curData);
      util.layerOpen2({
        title: '修改泊车位',
        content: $layerStationParkingDetail,
        area: ['800px', ''],
        btn: ['修改', '取消'],
        yes: function (index) {
          var data = util.formData($formStationParking);
          data.kid = curData.kid;
          data.cityId = curCityId;
          data.stationId = curStationId;

          if ($valiateStationParking.form()) {
            layer.confirm('确定修改该泊车位？', function () {
              util.post(ajaxURL.ORGANIZATION + '/station/updateStationParking', data, function (res) {
                getStationParking(curStationId, function () {
                  layer.close(index);
                  util.tip.success('修改成功');
                });
              });
            });
          }
        }
      });
    });

    // 删除站点泊车位
    $layerStationParking.on('click', '.station-parking-del', function () {
      var id = $(this).parent().data('kid');
      layer.confirm('确定删除该站点泊车位？', function () {
        util.post(ajaxURL.ORGANIZATION + '/station/removeStationParking?kid=' + id, function (res) {

          getStationParking(curStationId, function () {
            util.tip.success('删除成功');
          });
        });
      });
    });

    // 商圈设置
    function openBusiness(id, name) {
      util.tip.warn('商圈设置...');
    }

    // 删除城市
    $cityList.on('click', '.city-del', function () {
      var $this = $(this);
      var id = $this.parents('.city-item').data('kid');
      var cityId = $this.parents('.city-item').data('cid');
      var name = $this.siblings('.city-name').text();

      // if (cityId === 4301 || cityId === 4201) {
      //   return util.tip.warn('该城市禁止删除');
      // };

      layer.confirm('城市删除后，和该城市相关设置都将失效，各端该城市的服务都将停用，请谨慎操作。', {
        title: '确认删除城市“' + name + '”吗？'
      }, function () {
        util.ajax(ajaxURL.ORGANIZATION + '/city/removeCity?kid=' + id, '', 'POST', util.resCallback(function (res) {
          getCityList(function () {
            util.tip.success('城市“' + name + '”删除成功');
          });
        }));
      });
    });

    var $layerCity = $('#layer-city');
    var $formCity = $('#form-city');
    var $newCityName = $('#new-city-name');
    var $validateCity = $formCity.validate({
      rules: {
        name: { required: true },
        manager: { required: true },
        managerPhone: { required: true },
      },
      messages: {
        name: { required: '请输入城市名称' },
        manager: { required: '请输入负责人姓名' },
        managerPhone: { required: '请输入负责人联系方式' }
      }
    });

    // 新增城市
    $('#city-add').click(function () {
      util.resetForm($formCity);

      // 过滤已有城市列表
      var validCityList = [];

      $.each(cityLists, function (_, item) {
        if (!cityData[item.id]) {
          validCityList.push(item);
        }
      });

      $newCityName.removeAttr('disabled').sinput({
        data: validCityList,
        text: 'name',
        extraData: ['id'],
        extraDataName: ['cityId']
      });

      util.layerOpen2({
        title: '新增城市',
        content: $layerCity,
        area: ['400px', ''],
        btn: ['新增', '取消'],
        yes: function (index) {
          var data = util.formData($formCity);
          data.kid = '';

          if ($validateCity.form()) {
            layer.confirm('确定新增城市“' + data.name + '”？', function () {
              util.ajax(ajaxURL.ORGANIZATION + '/city/addCity', JSON.stringify(data), 'POST', util.resCallback(function (res) {
                getCityList(function () {
                  $newCityName.val('').next().val('');
                  layer.close(index);
                  util.tip.success('城市“' + name + '”新增成功');
                });
              }));
            });
          }
        }
      }, true);
    });

    // 城市的查看与修改
    $cityList.on('click', '.city-detail', function () {
      var $this = $(this);
      var cityId = $this.parents('.city-item').data('cid');
      var name = $this.siblings('.city-name').text();

      var curData = cityData[cityId];
      util.resetForm($formCity);
      util.fillForm($formCity, curData);

      $newCityName.attr('disabled', 'disabled');

      util.layerOpen2({
        title: '查看/修改城市信息',
        content: $layerCity,
        area: ['400px', ''],
        btn: ['修改', '关闭'],
        yes: function (index) {
          var data = util.formData($formCity);
          // 补正城市编号
          data.cityId = curData.cityId;

          if ($validateCity.form()) {
            layer.confirm('确定修改该城市信息？', function () {
              util.ajax(ajaxURL.ORGANIZATION + '/city/updateCity', JSON.stringify(data), 'POST', util.resCallback(function (res) {
                layer.close(index);
                util.tip.success('修改成功');
                // 直接更新数据，不进行重新请求
                $.extend(cityData[cityId], {
                  manager: data.manager,
                  managerPhone: data.managerPhone
                });
                // getCityList(function () {
                //   $newCityName.val('').next().val('');
                //   layer.close(index);
                //   util.tip.success('修改成功');
                // });
              }));
            });
          }
        }
      });

    });

    // 地图选址
    util.dragMap({
      selector: [
        '#pick-aiport-address',
        '#pick-terminal-address',
        '#pick-station-address',
        '#pick-station-exit-address'
      ],
      init: [
        function (map) {
          // 设置地图中心
          map.setCity(cityData[curCityId].name);
        },
        null,
        function (map) {
          // 设置地图中心
          map.setCity(cityData[curCityId].name);
        }
      ],
      callback: function (data, $elem) {
        $elem.siblings('[name="lng"]').val(data.position.lng).focus();
        $elem.siblings('[name="lat"]').val(data.position.lat).focus().blur();
        // 末尾添加事件用于触发可能的验证规则
      }
    });


  });


})(window, jQuery);
